package rpg.core
{
	import rpg.Utils.GameUtils;
	import rpg.animation.Animation;
	import rpg.animation.Frame;
	import rpg.role.SceneObject;

	public class AnimationComponent extends RenderComponent
	{
		protected var animation : Animation;
		protected var animationDelay : int;
		protected var runTimes : int;
		public var animationID : String;
		public var isAutoDestroy : Boolean = true;
		protected var rotation : int;

		public function AnimationComponent(type : * = null)
		{
			super(type == null ? AnimationComponent : type);
		}

		public function setAnimation(animation : Animation , zIndex : int , playDelay : int = 0 , loops : int = 0) : void
		{
			this.animation = animation;
			if(animation == null)
				return;
			animationDelay = playDelay;
			animationID = animation.id;
			animation.loops = loops;
			render.zIndex = zIndex;
		}

		override public function update(delay : uint) : void
		{
			if(animation == null)
				return;
			runTimes += delay;
			if(runTimes > animationDelay)
			{
				animation.tryNext(delay);
				updateRender(sceneObj.mapX - GameUtils.viewX , sceneObj.mapY - GameUtils.viewY , offsetX , offsetY);
			}
			if(animation.loops == 1 && animation.isEnd)
			{
				if(isAutoDestroy)
					destroy();
				else
					clear();
			}
		}

		override public function updateRender(sceneX : int , sceneY : int , offsetX : int = 0 , offsetY : int = 0) : void
		{
			var frame : Frame = animation.curFrame;
			if(frame.data == null && frame.frameClass)
			{
				frame.data = new frame.frameClass(0 , 0);
			}
			render.bitmapData = frame.data;
			render.x = sceneX + frame.offsetX - offsetX;
			render.y = sceneY + frame.offsetY - offsetY;
			if(rotation)
				render.rotate(rotation , -frame.offsetX , -frame.offsetY);
		}

		/**
		 * 是旋转
		 * @param value
		 *
		 */
		public function setRotate(value : int) : void
		{
			rotation = value;
		}

		/**
		 * 清除
		 *
		 */
		public function clear() : void
		{
			if(sceneObj)
				sceneObj.removeComponent(this);
			if(animation)
				animation.gotoFrame(0);
			sceneObj = null;
		}

		override public function destroy() : void
		{
			super.destroy();
			if(animation)
				animation.destroy();
			animation = null;
		}
	}
}